package com.rom.tree.HuffmanTree;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author YLNO
 * @version 1.0
 * @date 2023/12/14 10:41
 * 构建huffman树    和    huffman树编码
 */
public class HuffmanTree {

    public static void main(String[] args) {

        int[] arr = {13,7,8,3,29,6,1};

        Node huffManTree = createHuffManTree(arr);

        preOrder(huffManTree);
    }

    //前序遍历
    public static void preOrder(Node node){

        if(node == null){
            System.out.println("为空");
            return;
        }
        node.preOrder();
    }

    public static Node createHuffManTree(int[] arr){

//        1.将arr转换为NodeArray
        ArrayList<Node> arrayList = new ArrayList<>();
        for (int value : arr) {
            arrayList.add(new Node(value));
        }

        //对Node节点进行排序
        Collections.sort(arrayList);
//        System.out.println(arrayList);
        //开始构建huffman树
        while(arrayList.size()>1){
//            取出arrayList的前两个值
            Node remove1 = arrayList.remove(0);
            Node remove2 = arrayList.remove(0);

            Node parent = new Node(remove1.getValue() + remove2.getValue());
            parent.setLeft(remove1);
            parent.setRight(remove2);

            arrayList.add(parent);

            Collections.sort(arrayList);
        }
        return arrayList.get(0);
    }
}


class Node implements Comparable<Node>{

    private int value;

    //左右指针
    private Node left;
    private Node right;

    public Node(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        //排序
        return this.value-o.value;
    }
    //前序遍历
    public void preOrder(){

        System.out.println(this);

        if(this.getLeft()!=null){
            this.getLeft().preOrder();
        }
        if(this.getRight()!=null){
            this.getRight().preOrder();
        }
    }
}
